package com.vogue.supplymall.common.domain.jacksonutil;

/**
 * Created by Administrator on 2018-01-23.
 */
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期型序列化
 */
public class DateSerializer extends DateTimeSerializerBase<Date> {

    public final static DateSerializer instance = new DateSerializer(Date.class,false,null);
    private static ThreadLocal<String> datepattern= new ThreadLocal<>();
    private static final String defpattern="yyyy-MM-dd HH:mm:ss";//默认转为字符串的格式

    private DateSerializer(Class<Date> type, Boolean useTimestamp, DateFormat customFormat) {
        super(type, useTimestamp, customFormat);
    }

    @Override
    public DateTimeSerializerBase<Date> withFormat(Boolean timestamp, DateFormat customFormat) {
        return this;
    }

    @Override
    protected long _timestamp(Date value) {
        return (value == null) ? 0L : value.getTime();
    }

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String pat=datepattern.get();
        if(StringUtils.isEmpty(pat)){
            pat=defpattern;
        }
        SimpleDateFormat sdf=new SimpleDateFormat(pat);
        gen.writeString(sdf.format(value));
    }

    public void setDateFormat(String pat){
        datepattern.set(pat);
    }
}